package me.dqn.floatingtraffic.service;

import android.app.Service;
import android.app.usage.NetworkStats;
import android.app.usage.NetworkStatsManager;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.TrafficStats;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

import me.dqn.floatingtraffic.R;
import me.dqn.floatingtraffic.bean.WindowSettings;
import me.dqn.floatingtraffic.views.FloatingWindow;

import static android.content.ContentValues.TAG;

public class BackService extends Service {
    private FloatingWindow floatingWindow = null;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.i(TAG, "onCreate: service");
        super.onCreate();
        if (floatingWindow == null) {
            floatingWindow = new FloatingWindow(BackService.this);
            floatingWindow.showFloatWindow();
        }
        new Thread(() -> {
            while (true) {
                try {
                    long speed = getSpeed();
                    Message message = new Message();
                    message.what = 1;
                    message.obj = speed + "KB";
                    floatingWindow.handler.sendMessage(message);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 返回平均每秒速度
     *
     * @return KBytes / s
     * @throws RemoteException
     */
    private long getSpeed() throws InterruptedException {
        long start = TrafficStats.getTotalRxBytes();
        Thread.sleep(WindowSettings.refreshTime);
        long end = TrafficStats.getTotalRxBytes();
        return (end - start) / 1024 / (WindowSettings.refreshTime / 1000);
    }

    @Override
    public void onDestroy() {
        stopForeground(true);
        Intent intent = new Intent(getString(R.string.BACK_SERVICE_NAME));
        sendBroadcast(intent);
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, START_STICKY_COMPATIBILITY, startId);
    }
}
